﻿using System;
using System.Collections.Generic;
using System.Windows.Input;
using PSE.Framework.UI.Resources;
using System.Linq;
using System.Windows;

namespace Sinacor.Infra.UI.Controls.SmartClient
{
    public partial class SinacorDataGrid
    {
        #region Tratamento de Eventos

        private void ExportReportCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            SinacorDataGrid grid = (SinacorDataGrid)sender;
            e.CanExecute = grid.IsExportableExcel && grid.CanExportReport();
            e.Handled = true;
        }

        private void ExportReportCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            SinacorDataGrid grid = (SinacorDataGrid)sender;
            grid.ExportReport();
        }

        #endregion

        #region ExportReport

        protected bool CanExportReport()
        {
            return !this.IsEditing && (this.Items.Count > 0);
        }

        public bool ExportReport()
        {
            if (this.CanExportReport())
            {
                SinacorWindow ownerWindow = Window.GetWindow(this) as SinacorWindow;
                SinacorReport sinacorReport = new SinacorReport(ownerWindow);

                //Classifica coluna pela ordem da exibição para no caso de troca de posição de colunas manualmente.
                IEnumerable<Column> columns = this.Columns.OrderBy(Column => Column.InternalColumn.VisiblePosition);

                if (this.ReportTitleResourceKey == null)
                    this.ReportTitleResourceKey = String.Empty;

                sinacorReport.Show(this.ItemsSource, columns, this.ReportTitleResourceKey);

                return false;
            }
            return false;
        }

        #endregion
    }
}
